using Admin2025.Infrastructure.Data;
using Admin2025.Domain.Entities.App;
using Admin2025.Domain.Repositories;
using Dapper;
using Admin2025.Domain.Common;

namespace Admin2025.Infrastructure.Repositories;

public class UserRepository : Repository<AppUser>, IUserRepository
{
    public UserRepository(Admin2025DbContext factory) : base(factory) { }

    public async Task<AppUser?> GetByUsernameAsync(string username)
    {
        var sql = "SELECT * FROM AppUsers WHERE Username = @Username";
        return await _db.QuerySingleOrDefaultAsync<AppUser>(sql, new { Username = username });
    }

    // 分页
    public async Task<PagedResult<AppUser>> GetUsersPagedAsync(PagedRequest request)
    {
        var sql = @"
            SELECT COUNT(1) FROM AppUsers;
            SELECT * FROM AppUsers
            ORDER BY Username
            OFFSET @Offset ROWS FETCH NEXT @PageSize ROWS ONLY;";

        using var multi = await _db.QueryMultipleAsync(sql, new
        {
            Offset = (request.PageNumber - 1) * request.PageSize,
            request.PageSize
        });

        var totalCount = await multi.ReadSingleAsync<int>();
        var users = (await multi.ReadAsync<AppUser>()).ToList();

        return new PagedResult<AppUser>
        {
            Items = users,
            TotalCount = totalCount,
            PageNumber = request.PageNumber,
            PageSize = request.PageSize
        };
    }

    public async Task CreateUserAsync(AppUser user)
    {
        var sql = @"
            INSERT INTO AppUsers (Id, Username, Email, PasswordHash)
            VALUES (@Id, @Username, @Email, @PasswordHash)";

        await _db.ExecuteAsync(sql, new
        {
            user.Id,
            user.UserName,
            user.Email,
            user.PasswordHash,
            // user.DepartmentId
        });
    }

    public async Task UpdateUserAsync(AppUser user)
    {
        var sql = @"
            UPDATE AppUsers
            SET Username = @Username,
                Email = @Email,
                PasswordHash = @PasswordHash
            WHERE Id = @Id";

        await _db.ExecuteAsync(sql, new
        {
            user.UserName,
            user.Email,
            user.PasswordHash,
            // user.DepartmentId,
            user.Id
        });
    }

    public async Task DeleteUserAsync(Guid id)
    {
        var sql = "DELETE FROM AppUsers WHERE Id = @Id";
        await _db.ExecuteAsync(sql, new { Id = id });
    }
}